<template>
    <div class="header-container box-shadow">
        <nav>
            <div class="left">
                <!-- 点击之后跳转到对应页面 -->
                <div class="weather-info" @click="handlePage">
                    <i
                        class="iconfont"
                        :class="getIconName(weather.weather)"
                    ></i>
                    <p class="text_2xl">{{ weather.province }}</p>
                </div>
                <h4 class="text_lg">{{ city }}</h4>
                <p class="text_sm">
                    实时天气：{{ weather.weather }} {{ weather.temperature }}℃
                </p>
                <p class="text_sm">西南风{{ weather.windpower }}级</p>
            </div>
            <div class="right">
                <!-- 关于 -->
                <i class="iconfont icon-guanyu" @click="handleAbout"></i>
                <!-- 添加收藏图标 -->
                <i class="iconfont icon-jiahao" @click="handleCollect" :class="{'display': isFavorite(getCurrentCity())}"></i>
            </div>
        </nav>
    </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import {
    getCityByIp,
    getTodayWeatherByAdcode,
    getAdcodeByCity,
} from "@/api/getData";
import { getIconName } from "@/utils/getIconName";
import { useRouter } from "vue-router";
import { useFavoritesStore } from "@/stores/favorites";
import { storeToRefs } from "pinia";

const city = ref("");
const weather = ref([]);
let adcode = ref("");
const error = ref(null);
const router = useRouter();
const favoritesStore = useFavoritesStore();
const { favorites } = storeToRefs(favoritesStore);

const emits = defineEmits(["handleAbout"]);
// 关于:自定义点击事件
const handleAbout = () => {
    emits("handleAbout", true);
};
// 判断当前城市是否在收藏列表中
const isFavorite = (city) => {
    return favorites.value.some(item => item == city);
};
// 收藏：如果不在收藏列表中，则添加到收藏列表中
const handleCollect = () => {
    if (!isFavorite(getCurrentCity())) {
        favoritesStore.addFavorite(getCurrentCity());
    }
};
const fetchWeatherData = async () => {
    try {
        // 获取当前城市
        city.value = await getCityByIp();
        // console.log("当前城市:", city.value);

        // 根据城市获取天气数据
        weather.value = await getTodayWeatherByAdcode(city.value);
        // console.log("天气数据:", weather.value);
    } catch (err) {
        error.value = err.message;
        console.error("获取数据失败:", err);
    }
};

// 点击之后跳转到搜索页面
const handlePage = async () => {
    // 判断当前页面是否是搜索页面，如果是则跳转到天气页面，否则跳转对应的城市的天气页面
    if (router.currentRoute.value.path === "/weather/") {
        adcode = await getAdcodeByCity(city.value);
        router.push({
            // 获取adcode
            path: `/weather/${adcode}`,
            query: { search: city.value },
        });
    } else {
        router.push("/weather/");
    }
};
// 获取当前查询城市
// 两种情况：1.从查看按钮跳转过来（可以根据query获取），2.从header跳转过来（可以根据ip获取）
const getCurrentCity = () => {
    if (router.currentRoute.value.query.search) {
        return router.currentRoute.value.query.search;
    } else {
        return city.value;
    }
}
onMounted(() => {
    fetchWeatherData();
});
</script>
<style scoped>
.header-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.header-container nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0 102px;
    padding: 10px 160px;
    width: 100%;
}
.header-container nav p {
    margin: 0 10px;
}
.header-container nav .left {
    display: flex;
    align-items: center;
}
.iconfont {
    font-size: 24px;
    margin-right: 8px;
}
.weather-info {
    display: flex;
    align-items: center;
    cursor: pointer;
}
.icon-guanyu,.icon-jiahao {
    color: #fff;
    width: 20px;
    height: 20px;
    cursor: pointer;
    transition: color 0.3s ease-in-out;
}
.icon-guanyu:hover,.icon-jiahao:hover {
    color: #004e71;
}
.display {
    display: none;
}
</style>
